<?php
/**
 * 考勤管理控制器
 * @author ZhouYP
 **/
namespace Admin\Controller;
use Common\Controller\WahahabaseController;
class ResultController extends WahahabaseController{
	protected $file_model,$type_model,$ves_model;

	public function _initialize() {
		parent::_initialize();
		$this->file_model = D("Common/Uploadfile");
		$this->type_model = D("Common/UploadfileType");
		$this->ves_model = D("Common/UploadfileVersion");
		
	}
	/**
     *  主页
     */
	public function index(){
		/* 搜索条件 */
		if($_GET['type_id'] != false){//类型筛选
			$_SESSION['type_id_res'] = $_GET['type_id'];
		}
		$type = $_SESSION['type_id_res'] ? $_SESSION['type_id_res'] : 'all';
		if($_GET['construction_id'] != false && $_GET['construction_id'] != $_SESSION['construction_id_res']){//阶段筛选
			$_SESSION['construction_id_res'] = $_GET['construction_id'];
			$_SESSION['version_id_res'] = 'all';
		}
		
		if($_GET['version_id'] != false){//版本筛选
			$_SESSION['version_id_res'] = $_GET['version_id'];
		}
		
		/*查询默认的阶段和版本 start*/
		$res = $this->file_model->alias("f")
            ->field('max(f.construction_id) max')
			->where('f.file_model = 3 ')
            ->find();
		$const = $res['max'] ? $res['max'] : 'all';
		$construction = $_SESSION['construction_id_res'] ? $_SESSION['construction_id_res'] : $const;
		if($_SESSION['construction_id_res'] == '' && $construction != 'all'){
			$ret = $this->file_model->alias("f")
				->field('max(f.version_id) max')
				->where('f.file_model = 3 AND f.construction_id = '.$construction)
				->find();
			$version = $_SESSION['version_id_res'] ? $_SESSION['version_id_res'] : $ret['max'];
		}else{//阶段选中，版本也是选中，如果未选中则全选
			$version = $_SESSION['version_id_res'] ? $_SESSION['version_id_res'] : 'all';
		}
		$version = $version ? $version : 'all';
		/*查询默认的阶段和版本 end */
		$file_name = trim($_POST['file_name']) ? trim($_POST['file_name']) : '';
		$where = " f.file_model = 3 ";
		if($type && $type != 'all'){//专业类型
			$where .= " and f.type_id = ".$type;
		}
		if($version && $version != 'all'){//版本
			$where .= " and f.version_id = ".$version;
		}
		if($construction && $construction != 'all'){//阶段
			$where .= " and f.construction_id = ".$construction;
		}
		if($file_name){//图纸名称或图号
			$where .= " and (f.file_name like '%".$file_name."%' or f.figure_num like '%".$file_name."%') ";
		}
		$count=$this->file_model->alias("f")->where($where)->count();
		$page = $this->page($count, 20);
        $results = $this->file_model->alias("f")
            ->field('f.*,u.real_name,d.department_name,s.version_name,t.type_name')
            ->join(array(
            	 ' LEFT JOIN '.C('DB_PREFIX').'uploadfile_type t ON t.id = f.type_id',
            	 ' LEFT JOIN '.C('DB_PREFIX').'uploadfile_version s ON s.id = f.version_id',
				 ' LEFT JOIN '.C('DB_PREFIX').'users u ON u.id = f.manager_id',
				 ' LEFT JOIN '.C('DB_PREFIX').'department d ON d.id=u.department_id',
            	))
            ->where($where)
            ->order("f.ordernum asc,f.upload_time desc")
            ->limit($page->firstRow, $page->listRows)
            ->select();
		$this->assign("results", $results);//传递总数据
		$types = $this->type_model->where(array('type_id'=>3))->order("id ASC")->select();
        $this->assign("types",$types);//传递分类数据
		$versions = $this->ves_model->where(array('type_id'=>3,'construction_id'=>$construction))->order("id ASC")->select();
        $this->assign("versions",$versions);//传递版本数据
		$this->assign("page", $page->show('Admin'));
		$this->assign("type_id",$type);
        $this->assign("version_id",$version);
		$this->assign("construction_id",$construction);
		$this->assign("file_name",$file_name);
        $this->display();
	}

	/**
     *  添加
     */
	public function add(){
		$types = $this->type_model->where(array('type_id'=>3))->order("id ASC")->select();
        $this->assign("types",$types);
		$versions = $this->ves_model->where(array('type_id'=>3,'construction_id'=>1))->order("id ASC")->select();
        $this->assign("versions",$versions);
		$this->display();
	}
	public function add_post2(){
		if(IS_POST){
			if(empty($_POST['file_name'])){
				$this->error("图纸名称不能为空！");
			}
			if(empty($_POST['upFile'])){
				$this->error("请选择要上传的图纸文件！");
			}var_dump($_POST);exit;
			if ($this->file_model->create()!==false) {
				$data = $_POST;
				$data['file_model'] = '1';
				$data['manager_id'] = session('ADMIN_ID');
				$data['upload_time'] = time();
				if($_POST['upExcel']){
					$this->import();
				}
				
				for($i = 0; $i < count($_POST['fileName']); $i++){
					$files = array(
						//'file_name'	=> $_POST['fileName'][$i],
						'file_path'	=> $_POST['filePath'][$i],
						'file_type'	=> $_POST['postfix'][$i],
						'file_size'	=> $_POST['file_size'][$i]/1000,
					);
					$data = array_merge($data, $files);
					$result = $this->file_model->add($data);
				}
				if ($result!==false) {
					$this->success("添加成功！", U("DrawingUpload/index"));
				} else {
					$this->error("添加失败！");
				}
			} else {
				$this->error($this->file_model->getError());
			}
		}
	}
	/*
	添加
	*/
	public function add_post(){
		if(IS_POST){
			if(empty($_FILES['upFile'])){
				$this->error("请选择要上传的成果文件！");
			}
			if ($this->file_model->create()!==false) {
				$data = $_POST;
				$data['file_model'] = '3';
				$data['manager_id'] = session('ADMIN_ID');
				$data['upload_time'] = time();
				//导入Excel信息
				if($_FILES['upExcel']['name'] != ''){
					$res = $this->uploadexcel();
					$ret = $this->import($res['rtnResult']);
				}
				//var_dump($ret);echo "<br>";var_dump($_FILES);exit;
				for($i = 0; $i < count($_FILES['upFile']['name']); $i++){
					//确定文件存储名称-excel中有的用表中的名称；表中没有则用输入的名称；
					if(!empty($ret) && $ret[$_FILES['upFile']['name'][$i]]['file_name'] != ''){
						$file_name = $_FILES['upFile']['name'][$i];
					}else{
						$file_name = $data['file_name'];
					}
					$return = $this->uploadfile($i,$file_name);
					$files = array(
						//'file_name'	=> $return['file_name'],
						'file_path'	=> $return['rtnResult'],
						'file_type'	=> $return['postfix'],
						'file_size'	=> $return['file_size']/1000,
					);
					if(!empty($ret) && $return['file_name'] == $ret[$return['file_name']]['file_name']){
						$files['ordernum'] = $ret[$return['file_name']]['ordernum'];
						$files['type_id'] = $ret[$return['file_name']]['type_id'];
						$files['figure_num'] = $ret[$return['file_name']]['figure_num'];
						$files['sheet'] = $ret[$return['file_name']]['sheet'];
						$files['sheets'] = $ret[$return['file_name']]['sheets'];
						$files['file_name'] = $ret[$return['file_name']]['file_name'];
					}
					//如果文件名没有对应的，就使用原名和默认数据
					if($data['file_name'] == ''){
						$files['file_name'] = $return['file_name'];
					}
					//处理文件名
					$pos = strrpos($files['file_name'],'.');
					if($pos != false){
						$files['file_name'] = str_replace('#', '', substr($files['file_name'],0,$pos));
					}
					$datas = array_merge($data, $files);
					$result = $this->file_model->add($datas);
				}
				if ($result!==false) {
					$this->success("添加成功！", U("Result/index"));
				} else {
					$this->error("添加失败！");
				}
			} else {
				$this->error($this->file_model->getError());
			}
		}
	}
	/*
	ajax获取版本
	*/
	public function get_versions(){
		$construction_id = $_GET['construction_id'];
		$versions = $this->ves_model->where(array('type_id'=>3,'construction_id'=>$construction_id))->order("id ASC")->select();
		echo json_encode($versions);
	}
	/**
	 *  删除图纸
	 */
	public function delete(){
	    $id = I('get.id',0,'intval');
		$d = $this->file_model->where(array('id' => $id))->find();
		//检测用户 非本人不能删除
		$admin_id = session('ADMIN_ID');
		if($admin_id != $d['manager_id']){
			$this->error("禁止删除他人文件！");
		}
        $file = __ROOT__.$d['file_path'];//同步删除文件
		if ($this->file_model->delete($id) !== false) {
			unlink($file);
			$this->success("删除成功！");
		} else {
			$this->error("删除失败！");
		}
	}
	
	/*
	修改图纸
	*/
	public function edit(){
		$id = I('get.id',0,'intval');
		if($id == false){
			$this->error("请先选择要编辑的文件！", U("Result/index"));
		}
		$result = $this->file_model->alias("f")
			->field('f.*')
			->where(array("f.id"=>$id))->find();
		if(empty($result)){
			$this->error("文件查找失败！", U("Result/index"));
		}
		$types = $this->type_model->where(array('type_id'=>3))->order("id ASC")->select();
        $this->assign("types",$types);//传递分类数据
		$versions = $this->ves_model->where(array('type_id'=>3,'construction_id'=>$result['construction_id']))->order("id ASC")->select();
        $this->assign("versions",$versions);//传递版本数据
		$this->assign("result", $result);
		
		$this->display();
	}
	/*
	修改图纸-数据处理
	*/
	public function edit_post($id){
		if (IS_POST) {
			$data = $_POST;
			if ($this->file_model->create()!==false) {
				$result=$this->file_model->where('id='.$id)->save($data);
				if ($result !== false) {
					$this->success("修改成功！", U("Result/index"));
				} else {
					$this->error("修改失败！");
				}
			} else {
				$this->error($this->file_model->getError());
			}
		}
	}
	/*
	新增版本
	*/
	public function add_version(){
		$types = $this->type_model->where(array('type_id'=>3))->order("id ASC")->select();
        $this->assign("types",$types);
		$versions = $this->ves_model->where(array('type_id'=>3,'construction_id'=>1))->order("id ASC")->select();
        $this->assign("versions",$versions);
		$this->display();
	}
	/*
	新增版本-数据处理
	*/
	public function add_version_post(){
		if (IS_POST) {
			$data = $_POST;
			$data['type_id'] = '3';
			$data['manager_id'] = session('ADMIN_ID');
			$data['add_time'] = time();
			//防重复查询
			$versions = $this->ves_model->where(array('type_id'=>1,'construction_id'=>$data['construction_id'],'version_name'=>$data['version_name']))->order("id ASC")->select();
			if(!empty($versions)){
				$this->error("添加失败,版本号重复！");
			}
			if ($this->ves_model->create()!==false) {
				$result=$this->ves_model->add($data);
				if ($result !== false) {
					$this->success("添加成功！", U("Result/add_version"));
				} else {
					$this->error("添加失败！");
				}
			} else {
				$this->error($this->ves_model->getError());
			}
		}
	}
	/*
     * 上传文件
     */
     public function uploadfile($i,$file_name){
        if(is_uploaded_file($_FILES['upFile']['tmp_name'][$i])){
            // 验证图片宽高信息
            $uploadSize = getimagesize($_FILES['upFile']['tmp_name'][$i]);
            $upfile = $_FILES["upFile"]; 
            //获取数组里面的值 
            $name = $upfile["name"][$i];//上传文件的文件名 
            $type = $upfile["type"][$i];//上传文件的类型 
            $size = $upfile["size"][$i];//上传文件的大小 
            $tmp_name = $upfile["tmp_name"][$i];//上传文件的临时存放路径 
            //处理文件名,有传入文件名则用，未传入就用原名
			if($file_name != false){
				$n = $file_name;
			}else{
				$n = $name;
			}
			$pos = strrpos($n,'.');
			if($pos != false){
				$fname = str_replace('#', '', iconv("UTF-8","gbk", substr($n,0,$pos)));
			}else{
				$fname = str_replace('#', '',iconv("UTF-8","GB2312",$n));
			}
            // 上传结果
            $rtnType = "F";
            $destination = "";
            $error = $upFile["error"][$i];//上传后系统返回的值 
            if($error == 0){
                
                // 获取文件后缀
                $pathinfo = pathinfo($name);
                
                $destination = "data/upload/"."upResult"."/".date('Ymd'); 
                if (! file_exists ( $destination )) {
                    mkdir ( "$destination", 0777, true );
                }
                $destination .= "/".$fname."_".time().rand(100,999).'.'.$pathinfo['extension'];
                // 如果有原始图片地址信息，删除图片
                if(file_exists($_POST['imageURL'])){
                    unlink($_POST['imageURL']);
                }
                // 如果有原始图片地址信息，删除图片
				if(file_exists($_POST['imageURL'])){
					unlink($_POST['imageURL']);
				}
				//var_dump($destination);exit;
                //把上传的临时文件移动到up目录下面 
                move_uploaded_file($tmp_name, $destination); 
                $rtnType = "T";
                $rtnMsg = "文件上传成功啦！";
            }elseif ($error == 1){ 
                $rtnMsg = "超过了文件大小，在php.ini文件中设置"; 
            }elseif ($error == 2){ 
                $rtnMsg = "超过了文件的大小MAX_FILE_SIZE选项指定的值"; 
            }elseif ($error == 3){ 
                $rtnMsg = "文件只有部分被上传"; 
            }elseif ($error == 4){ 
                $rtnMsg = "没有文件被上传"; 
            }else{ 
                $rtnMsg = "上传文件大小为0"; 
            } 
            
            // 输出结果
            $return = array(
                'rtnType'	=> $rtnType,
                'rtnMsg'	=> $rtnMsg,
                'rtnResult'	=> iconv("GB2312","UTF-8",$destination),
                'file_name'	=> $name,
                'file_size'	=> $size,
                'postfix'	=> $pathinfo['extension'],
                'file_type' => $type
            );
			return $return;
            //return $file_name = $name;
        } else {
            // 输出结果
            //exit(json_encode(array(
            //    'rtnType'	=> "F",
            //    'rtnMsg'	=> "请选择上传文件"
            //)));
			$this->error("请选择上传文件");
        }
    }
	/*
     * 上传文件
     */
     public function uploadexcel(){
        if(is_uploaded_file($_FILES['upExcel']['tmp_name'])){
            // 验证图片宽高信息
            $uploadSize = getimagesize($_FILES['upExcel']['tmp_name']);
            $upfile = $_FILES["upExcel"]; 
            //获取数组里面的值 
            $name = $upfile["name"];//上传文件的文件名 
            $type = $upfile["type"];//上传文件的类型 
            $size = $upfile["size"];//上传文件的大小 
            $tmp_name = $upfile["tmp_name"];//上传文件的临时存放路径 
            
            // 上传结果
            $rtnType = "F";
            $destination = "";
            $error = $upFile["error"];//上传后系统返回的值 
            if($error == 0){
                
                // 获取文件后缀
                $pathinfo = pathinfo($name);
                
                $destination = "data/upload/"."upExcel/".date('Ymd'); 
                if (! file_exists ( $destination )) {
                    mkdir ( "$destination", 0777, true );
                }
                $destination .= "/".time().'.'.$pathinfo['extension'];
                // 如果有原始图片地址信息，删除图片
                if(file_exists($_POST['imageURL'])){
                    unlink($_POST['imageURL']);
                }
                // 如果有原始图片地址信息，删除图片
				if(file_exists($_POST['imageURL'])){
					unlink($_POST['imageURL']);
				}
				
                //把上传的临时文件移动到up目录下面 
                move_uploaded_file($tmp_name, $destination); 
                $rtnType = "T";
                $rtnMsg = "文件上传成功啦！";
            }elseif ($error == 1){ 
                $rtnMsg = "超过了文件大小，在php.ini文件中设置"; 
            }elseif ($error == 2){ 
                $rtnMsg = "超过了文件的大小MAX_FILE_SIZE选项指定的值"; 
            }elseif ($error == 3){ 
                $rtnMsg = "文件只有部分被上传"; 
            }elseif ($error == 4){ 
                $rtnMsg = "没有文件被上传"; 
            }else{ 
                $rtnMsg = "上传文件大小为0"; 
            } 
            
            // 输出结果
            $res = array(
                'rtnType'	=> $rtnType,
                'rtnMsg'	=> $rtnMsg,
                'rtnResult'	=> $destination,
                'file_name'	=> $name,
                'file_size'	=> $size,
                'postfix'	=> $pathinfo['extension'],
                'file_type' => $type
            );
            //return $file_name = $name;
			return $res;
        } else {
            // 输出结果
            //exit(json_encode(array(
            //    'rtnType'	=> "F",
            //    'rtnMsg'	=> "请选择上传文件"
            //)));
			$this->error("请选择上传文件");
        }
    }
	/*
	 * 导入数据
	 * 工程项目报价汇总表  
	 **/
	public function import($filePath){
		require_once SPAPP_PATH.'Core/Library/Vendor/PHPExcel/PHPExcel.php';
		require_once SPAPP_PATH.'Core/Library/Vendor/PHPExcel/PHPExcel/Writer/Excel5.php';// 用于其他低版本xls 
		require_once SPAPP_PATH.'Core/Library/Vendor/PHPExcel/PHPExcel/Writer/Excel2007.php';// 用于 excel-2007 格式
		  
		//$filePath = $_POST['upExcel']['filePath'];
		$PHPExcel = new \PHPExcel();//实例化，一定要注意命名空间的问题加\ 

		/**默认用excel2007读取excel，若格式不对，则用之前的版本进行读取*/ 
		$PHPReader = new \PHPExcel_Reader_Excel2007(); 
		if(!$PHPReader->canRead($filePath)){ 
			$PHPReader = new \PHPExcel_Reader_Excel5(); 
			if(!$PHPReader->canRead($filePath)){ 
				$this->error('文件读取失败');
				return; 
			} 
		}
		//不需要读取整个Excel文件而获取所有工作表数组的函数
		$sheetNames  = $PHPReader->listWorksheetNames($filePath);
		$PHPExcel = $PHPReader->load($filePath);
		// 保存数组
		$savedata = array();
		for($i = 0; $i < count($sheetNames); $i++){
			//读取excel文件中的第一个工作表 
			$currentSheet = $PHPExcel->getSheet($i);
			//取得一共有多少行
			$allRow = $currentSheet->getHighestRow();
			$allColumn = $currentSheet->getHighestColumn();
			/**从第二行开始输出，因为excel表中第一行为列名*/ 
			for($currentRow = 2; $currentRow <= $allRow; $currentRow++){
				$file_name = trim($currentSheet->getCell("D".$currentRow)->getValue());
				if($file_name != ''){
					$savedata[$file_name]['ordernum']	= $currentSheet->getCell("A".$currentRow)->getValue();;
					$savedata[$file_name]['type_id']	= $currentSheet->getCell("B".$currentRow)->getValue();
					$savedata[$file_name]['figure_num']	= $currentSheet->getCell("C".$currentRow)->getValue();
					$savedata[$file_name]['file_name']	= $file_name;
					$savedata[$file_name]['sheet']	= $currentSheet->getCell("E".$currentRow)->getValue();
					$savedata[$file_name]['sheets']	= $currentSheet->getCell("F".$currentRow)->getValue();
				}
				
			}
		}
		return $savedata;
		// 导入完成 删除文件
		//unlink($filePath);
	}
	
}


?>